
package com.crowdfunding.circle.trade.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crowdfunding.circle.common.controller.BaseController;
import com.crowdfunding.circle.common.param.SessionUserInfo;
import com.crowdfunding.circle.trade.entity.TradeRecordVO;
import com.crowdfunding.circle.trade.param.TradeRecordParam;
import com.crowdfunding.circle.trade.service.TradeRecordService;
import com.crowdfunding.circle.user.entity.UserInfoVO;
import com.crowdfunding.circle.user.service.UserInfoService;

/**
 * 费用收支记录，包括拆解查看交易记录，问题提问交易,偷看交易Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class TradeRecordController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(TradeRecordController.class);

    @Autowired
    private TradeRecordService tradeRecordService;

    @Autowired
    private UserInfoService userInfoService;

    private final static String ADMIN_LIST_PAGE = "/admin/trade_manage";
    
    private final static String UPDATE_PAGE = "/trade/trade_edit";
    
    @RequestMapping(value = "/admin/trade/toInsert")
    public ModelAndView intoInsert(String tradeTargetId, Integer tradeType) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        TradeRecordVO tradeRecordVO = tradeRecordService.getInitData(tradeTargetId, tradeType);
        resultMap.put("tradeRecord", tradeRecordVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/admin/trade/toUpdate/{id}")
    public ModelAndView intoUpdate(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        TradeRecordVO tradeRecordVO = tradeRecordService.findById(id);
        resultMap.put("tradeRecord", tradeRecordVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/admin/trade/update", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(TradeRecordVO tradeRecordVO) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer affectCount = 0;
            
            if (tradeRecordVO != null && StringUtils.isNotBlank(tradeRecordVO.getTradeId())) {
                affectCount = tradeRecordService.update(tradeRecordVO);
            } else if (tradeRecordVO != null) {
                
                List<UserInfoVO> oldUserList = userInfoService.queryUserByName(tradeRecordVO.getBuyUserName(), null);
                
                if (oldUserList != null && oldUserList.size() == 1) {
                    tradeRecordVO.setBuyUser(oldUserList.get(0).getUserId());
                } else {
                    resultMap.put("result", false);
                    resultMap.put("message", "根据昵称未找到对应用户");
                }
                tradeRecordVO.setTradeId(UUID.randomUUID().toString());
                tradeRecordVO.setPublishUser(seUser.getUserId());
                tradeRecordVO.setDataStatus(0);
                tradeRecordVO.setTradeTime(new Date(System.currentTimeMillis()));
                affectCount = tradeRecordService.insert(tradeRecordVO);
            }
            if (affectCount != null && affectCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改费用收支记录成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改费用收支记录失败");
            }
        } catch (Exception e) {
            logger.error("新增或修改费用收支记录出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改费用收支记录出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/admin/trade/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = tradeRecordService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除费用收支记录成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除费用收支记录失败");
            }
        } catch (Exception e) {
            logger.error("删除费用收支记录出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除费用收支记录出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/admin/trade/list")
    public ModelAndView queryList(TradeRecordParam tradeRecordParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<TradeRecordVO> dataList = tradeRecordService.queryByPage(tradeRecordParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", tradeRecordParam);
        return new ModelAndView(ADMIN_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/admin/trade/paySaleUser/{id}")
    public ModelAndView viewConfigInfo(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        TradeRecordVO tradeRecordVO = tradeRecordService.findById(id);
        if (tradeRecordVO.getTradeState() == 1) {
            tradeRecordVO.setTradeState(2);
        }
        resultMap.put("tradeRecord", tradeRecordVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
}
